﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using BTM_Client_Application.SupportClasses;
using BTM_Client_DBwork;
using BTM_Client_DBwork.Constants;
using Client_Server_Interface;
using FluentNHibernate.Infrastructure;

namespace BTM_Client_Application
{
    /// <summary>
    /// Логика взаимодействия для OptionsWindow.xaml
    /// </summary>

    public class SavedOptions
    {
        public bool UseLocalMarkers { get; set; }
    }

    public delegate void VoidSavedOptionsDelegate(SavedOptions opts);

    public partial class OptionsWindow
    {

        public event VoidSavedOptionsDelegate OptionsSaved;

        protected virtual void OnOptionsSaved(SavedOptions opts)
        {
            VoidSavedOptionsDelegate handler = OptionsSaved;
            if (handler != null) handler(opts);
        }

        public string SecondsString { get; set; }

        public OptionsWindow()
        {
            InitializeComponent();
            DataContext = this;
            Init();
        }

        void Init()
        {
            Title = Res.Rm.GetString("Parameters", AliveInfo.CurrentCulture);
            SecondsString = Res.Rm.GetString("Sec", AliveInfo.CurrentCulture) + '.';
            GeneralGroupBox.Header = Res.Rm.GetString("GeneralOptionsGroup");
            StatusTimeoutLabel.Content = Res.Rm.GetString("StatusTimeoutLabel", AliveInfo.CurrentCulture);
            UseLocalCoordsLabel.Content = Res.Rm.GetString("UseLocalCoordsLabel", AliveInfo.CurrentCulture);
            SoundOnLabel.Content = Res.Rm.GetString("Sound", AliveInfo.CurrentCulture);
            SaveButton.Content = Res.Rm.GetString("Save", AliveInfo.CurrentCulture);
            CancelButton.Content = Res.Rm.GetString("Cancel", AliveInfo.CurrentCulture);
            StatusLabel.Opacity = 0;

            try
            {
                UpdateValues();
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    Res.Rm.GetString("GetOptionsError", AliveInfo.CurrentCulture) + "." + Environment.NewLine +
                    ex.Message, Res.Rm.GetString("Warning"));
            }
            
        }

        void UpdateValues()
        {
            var statusTimeout = AliveInfo.DBwork.GetParameterValue(OptionNames.STATUS_REQUEST_PERIOD);
            int ival;
            if(int.TryParse(statusTimeout, out ival))
                StatusTimeoutBox.Text = statusTimeout;
            else
                StatusTimeoutBox.Text = "-1";
            var useLocalMarkers = AliveInfo.DBwork.GetParameterValue(OptionNames.USE_LOCAL_MARKER_POSITIONS);
            bool bval;
            if (bool.TryParse(useLocalMarkers, out bval))
                UseLocalCoordsBox.IsChecked = bval;
            else
                UseLocalCoordsBox.IsChecked = false;

            var soundOn = AliveInfo.DBwork.GetParameterValue(OptionNames.SOUND_ON);
            if (bool.TryParse(soundOn, out bval))
                SoundOnBox.IsChecked = bval;
            else
                SoundOnBox.IsChecked = true;
        }

        private void OptionsWindow_OnClosing(object sender, CancelEventArgs e)
        {
            Hide();
            e.Cancel = true;
        }

        private string _prevStatusTimeout = "0";
        private void StatusTimeoutBox_OnTextChanged(object sender, TextChangedEventArgs e)
        {
            var tb = sender as TextBox;
            int val;
            if (!int.TryParse(tb.Text, out val))
            {
                int c = tb.CaretIndex;
                tb.Text = _prevStatusTimeout;
                if (tb.Text.Length < c)
                    tb.CaretIndex = tb.Text.Length;
                else
                    tb.CaretIndex = c;
            }
            else
            {
                _prevStatusTimeout = tb.Text;
            }
        }

        void SaveOptions()
        {
            var allOk = true;
            var chk = AliveInfo.DBwork.SetParameter(OptionNames.STATUS_REQUEST_PERIOD, StatusTimeoutBox.Text);
            if (!chk) allOk = false;
            chk = AliveInfo.DBwork.SetParameter(OptionNames.USE_LOCAL_MARKER_POSITIONS, UseLocalCoordsBox.IsChecked.ToString());
            if (!chk) allOk = false;
            chk = AliveInfo.DBwork.SetParameter(OptionNames.SOUND_ON, SoundOnBox.IsChecked.ToString());
            if (!chk) allOk = false;
            //
            OnOptionsSaved(new SavedOptions {UseLocalMarkers = UseLocalCoordsBox.IsChecked == true});
            if (allOk)
            {
                SetStatus(Res.Rm.GetString("OptionsSaved"));
            }
            else
            {
                SetStatus("Error", false);
            }
        }

        void SetStatus(string text, bool ok = true)
        {
            StatusLabel.Content = text;
            StatusLabel.Opacity = 1;
            if (ok)
            {
                StatusLabel.Foreground = new SolidColorBrush(Colors.Green);
                var sb = new Storyboard();
                var da = new DoubleAnimation(1, 0, new Duration(new TimeSpan(0, 0, 3)));
                Storyboard.SetTargetProperty(da, new PropertyPath(OpacityProperty));
                sb.Children.Add(da);
                StatusLabel.BeginStoryboard(sb);
            }
            else
            {
                StatusLabel.Foreground = new SolidColorBrush(Colors.Red);
            }
        }

        private void SaveButton_OnClick(object sender, RoutedEventArgs e)
        {
            SaveOptions();
        }

        private void CancelButton_OnClick(object sender, RoutedEventArgs e)
        {
            UpdateValues();
            Close();
        }

        private void OptionsWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            UpdateValues();
        }

        private void SoundOnBox_OnChecked(object sender, RoutedEventArgs e)
        {
            SoundOnBox.Content = Res.Rm.GetString("On", AliveInfo.CurrentCulture) + '.';
        }

        private void SoundOnBox_OnUnchecked(object sender, RoutedEventArgs e)
        {
            SoundOnBox.Content = Res.Rm.GetString("Off", AliveInfo.CurrentCulture) + '.';
        }
    }
}
